using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    /// <summary>
    /// 批量删除工序处理器
    /// </summary>
    public class DeleteRouteStepsHandler : IRequestHandler<DeleteRouteStepsCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<RouteStepModel> _routeStepRepository;
        private readonly ILogger<DeleteRouteStepsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DeleteRouteStepsHandler(
            IBaseRepository<RouteStepModel> routeStepRepository,
            ILogger<DeleteRouteStepsHandler> logger)
        {
            _routeStepRepository = routeStepRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除工序命令
        /// </summary>
        public async Task<ApiResult<bool>> Handle(DeleteRouteStepsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.StepIds == null || !request.StepIds.Any())
                {
                    return new ApiResult<bool> { Msg = "请提供要删除的工序ID", Code = ApiEnum.Fail, Data = false };
                }

                // 验证工序是否存在
                var existingSteps = _routeStepRepository.GetAll()
                    .Where(x => request.StepIds.Contains(x.Id))
                    .ToList();

                if (!existingSteps.Any())
                {
                    return new ApiResult<bool> { Msg = "未找到要删除的工序", Code = ApiEnum.Fail, Data = false };
                }

                var notFoundIds = request.StepIds.Except(existingSteps.Select(x => x.Id)).ToList();
                if (notFoundIds.Any())
                {
                    _logger.LogWarning($"以下工序ID不存在: {string.Join(", ", notFoundIds)}");
                }

                // 执行批量删除
                await _routeStepRepository.DeleteBatchAsync(existingSteps);

                var deletedCount = existingSteps.Count;
                _logger.LogInformation($"批量删除工序成功，删除数量: {deletedCount}, 工序IDs: [{string.Join(", ", existingSteps.Select(x => x.Id))}], OperateBy: {request.OperateBy}");

                return new ApiResult<bool> 
                { 
                    Msg = $"成功删除 {deletedCount} 个工序", 
                    Code = ApiEnum.Success, 
                    Data = true 
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量删除工序失败，工序IDs: [{string.Join(", ", request.StepIds)}]");
                return new ApiResult<bool> { Msg = "批量删除工序失败", Code = ApiEnum.Fail, Data = false };
            }
        }
    }
} 